package manage.service;

import m.common.model.util.*;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.db.DBManager;
import m.system.db.DataRow;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.model.MenuInfo;
import manage.model.ModuleInfo;

import java.sql.SQLException;
import java.util.List;

public class ModuleService extends Service {
	
	public String fillModulesJSON(String key,JSONMessage json,String adminOid,String orgGroupOid,boolean hasDesc) throws SQLException, MException {
		String defaultMenuOid=null;
		String orgOid=StringUtil.noSpace(orgGroupOid);
		List<ModuleInfo> moduleList=getModuleList(adminOid,orgOid);
		JSONMessage modules=new JSONMessage();
		for(ModuleInfo moduleInfo : moduleList){
			if(!StringUtil.isSpace(moduleInfo.getUrlPath())&&null==defaultMenuOid)
				defaultMenuOid=moduleInfo.getOid();
			JSONMessage module=new JSONMessage();
			module.push("oid", moduleInfo.getOid());
			module.push("name", moduleInfo.getName());
			module.push("type", moduleInfo.getType());
			module.push("icon", moduleInfo.getIcoStyle());
			module.push("link", !StringUtil.isSpace(moduleInfo.getUrlPath()));
			JSONMessage menus1=new JSONMessage();
			List<MenuInfo> menulist1=getMenuList(adminOid,orgOid,moduleInfo.getOid(),"");
			if(menulist1.size()>0){
				for(MenuInfo menuInfo1 : menulist1){
					if(!StringUtil.isSpace(menuInfo1.getUrlPath())&&null==defaultMenuOid)
						defaultMenuOid=menuInfo1.getOid();
					JSONMessage menu1=new JSONMessage();
					menu1.push("oid", menuInfo1.getOid());
					menu1.push("name", menuInfo1.getName());
					if(hasDesc) menu1.push("desc", menuInfo1.getDescription());
					menu1.push("icon", menuInfo1.getIcoStyle());
					menu1.push("link", !StringUtil.isSpace(menuInfo1.getUrlPath()));
					List<MenuInfo> menulist2=getMenuList(adminOid,orgOid,moduleInfo.getOid(),menuInfo1.getOid());
					if(menulist2.size()>0){
						JSONMessage menu2=new JSONMessage();
						for(MenuInfo menuInfo2 : menulist2){
							if(!StringUtil.isSpace(menuInfo2.getUrlPath())&&null==defaultMenuOid)
								defaultMenuOid=menuInfo2.getOid();
							JSONMessage menu=new JSONMessage();
							menu.push("oid", menuInfo2.getOid());
							menu.push("name", menuInfo2.getName());
							if(hasDesc) menu.push("desc", menuInfo2.getDescription());
							menu.push("icon", menuInfo2.getIcoStyle());
							menu.push("link", !StringUtil.isSpace(menuInfo2.getUrlPath()));
							menu2.push(menuInfo2.getOid(), menu);
						}
						menu1.push("menus", menu2);
					}
					menus1.push(menuInfo1.getOid(), menu1);
				}
				module.push("menus", menus1);
			}
			modules.push(moduleInfo.getOid(), module);
		}
		if(moduleList.size()==0){
			JSONMessage module=new JSONMessage();
			module.push("oid", "A");
			module.push("name", "无菜单");
			module.push("icon", "");
			module.push("link", "page/blank.js");
			modules.push("A", module);
			defaultMenuOid="A";
		}
		json.push(key, modules);
		return defaultMenuOid;
	}

	/**
	 * 获取当前菜单的地址， 根据admin
	 */
	public String getMenuUrl(String oid,String adminOid,String orgGroupOid) {
		String orgOid=StringUtil.noSpace(orgGroupOid);
		List<ModuleInfo> moduleList=getModuleList(adminOid,orgOid);
		for(ModuleInfo module : moduleList){
			if(oid.equals(module.getOid())){
				return module.getUrlPath();
			}
			List<MenuInfo> m1List=getMenuList(adminOid,orgOid,module.getOid(),"");
			for(MenuInfo m1 : m1List){
				if(oid.equals(m1.getOid())){
					return m1.getUrlPath();
				}
				List<MenuInfo> m2List=getMenuList(adminOid,orgOid,module.getOid(),m1.getOid());
				for(MenuInfo m2 : m2List){
					if(oid.equals(m2.getOid())){
						return m2.getUrlPath();
					}
				}
			}
		}
		return null;
	}
	/**
	 * 获取管理员模块
	 */
	public List<ModuleInfo> getModuleList(String adminOid,String orgGroupOid){
		return CacheUtil.getList(ModuleInfo.class,adminOid+","+orgGroupOid);
	}

	/**
	 * 获取所有模块
	 */
	public List<ModuleInfo> getModuleList() throws SQLException, MException{
		return ModelQueryList.getModelList(ModuleInfo.class, 
				new String[]{"oid","name","type","urlPath","icoStyle","isPublic"},
				null,
				null, 
				QueryOrder.asc("sort")
			);
	}
	/**
	 * 获取管理员模块下的所有菜单或者模块下菜单的子菜单
	 */
	public List<MenuInfo> getMenuList(String adminOid,String orgGroupOid,String module_oid,String menu_oid) {
		return CacheUtil.getList(MenuInfo.class,adminOid+","+orgGroupOid+","+module_oid+","+menu_oid);
	}

	/**
	 * 获取模块下所有菜单
	 */
	public List<MenuInfo> getMenuList(String module_oid) throws SQLException, MException {
		return ModelQueryList.getModelList(MenuInfo.class,
				new String[]{"oid","name","urlPath","icoStyle","isPublic","description"},
				null,
				QueryCondition.and(
					QueryCondition.eq("moduleInfo.oid", module_oid),
					QueryCondition.isEmpty("parentMenu.oid")),
				QueryOrder.asc("sort")
			);
	}

	/**
	 * 获取模块菜单下所有菜单
	 */
	public List<MenuInfo> getMenuList(String module_oid,String menu_oid) throws SQLException, MException {
		return ModelQueryList.getModelList(MenuInfo.class,
				new String[]{"oid","name","urlPath","icoStyle","isPublic","description"},
				null,
				QueryCondition.and(
					QueryCondition.eq("moduleInfo.oid", module_oid),
					QueryCondition.eq("parentMenu.oid", menu_oid)
				),
				QueryOrder.asc("sort")
			);
	}

	private static final char[] newOids=new char[]{'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	private String getNewModuleOid() throws SQLException, MException {
		DataRow row=DBManager.queryFirstRow("SELECT max(oid) oid FROM os_module_info");
		if(null!=row){
			char oid=row.get(String.class,"oid").charAt(0);
			for (char newOid : newOids) {
				if (oid < newOid) {
					return String.valueOf(newOid);
				}
			}
			throw new MException(this.getClass(),"无法再创建模块了");
		}
		return "O";
	}
	public String saveModule(ModuleInfo module) throws SQLException, MException {
		String msg;
		ModelCheckUtil.checkNotNull(module, "name");
		ModelCheckUtil.checkUniqueCombine(module, new String[]{"name"});
		if(StringUtil.isSpace(module.getOid())){
			module.setOid(getNewModuleOid());
			ModelUpdateUtil.insertModel(module);
			msg="保存成功";
		}else{
			ModelUpdateUtil.updateModel(module, "name","type","urlPath","icoStyle","sort");
			msg="修改成功";
		}
		return msg;
	}
	private String getNewMenuOid(String parentOid,String moduleOid) throws Exception {
		if(!StringUtil.isSpace(parentOid)){
			DataRow row=DBManager.queryFirstRow("SELECT max(oid) oid FROM os_menu_info where parent_menu_oid=?",parentOid);
			if(null!=row){
				if(null==row.get("oid")) return parentOid+"51";
				int num=Integer.parseInt(row.get(String.class,"oid").substring(3));
				if(num<100){
					if(num<50) num=50;
					return parentOid+(num+1);
				}
				throw new MException(this.getClass(),"无法再创建菜单了");
			}
		}else if(!StringUtil.isSpace(moduleOid)){
			DataRow row=DBManager.queryFirstRow("SELECT max(oid) oid FROM os_menu_info where module_oid=? and (parent_menu_oid='' or parent_menu_oid is null)",moduleOid);
			if(null!=row){
				if(null==row.get("oid")) return moduleOid+"51";
				int num=Integer.parseInt(row.get(String.class,"oid").substring(1));
				if(num<100){
					if(num<50) num=50;
					return moduleOid+(num+1);
				}
				throw new MException(this.getClass(),"无法再创建菜单了");
			}
		}
		throw new MException(this.getClass(),"参数错误");
	}
	public String saveMenu(MenuInfo menu) throws Exception {
		String msg;
		ModelCheckUtil.checkNotNull(menu, "name");
		ModelCheckUtil.checkUniqueCombine(menu, new String[]{"name"});
		if(StringUtil.isSpace(menu.getOid())){
			menu.setOid(getNewMenuOid(menu.getParentMenu().getOid(),menu.getModuleInfo().getOid()));
			ModelUpdateUtil.insertModel(menu);
			msg="保存成功";
		}else{
			ModelUpdateUtil.updateModel(menu, "name","urlPath","icoStyle","sort");
			msg="修改成功";
		}
		return msg;
	}
}
